<?php

class BlockController extends BaseController {

  /**
   * Adds a new block.
   * @return Redirect
   */
  public function addBlock() {
    $block                 = new Block;
    $block->title          = Input::get('name');
    $block->tempestuser_id = Auth::user()->id;
    $block->page_id        = intval(Input::get('page_id'));
    $block->x              = 100;
    $block->y              = 100;

    // save and redirect.
    $validator = Validator::make($block->toArray(), Block::$rules);
    if ($validator->fails()) {
      Session::flash('error', $validator->messages()->first());
      Session::flash('currentPage', Input::get('page_id'));
      return Redirect::to('/');
    }

    $block->save();
    Session::flash('currentPage', Input::get('page_id'));
    Session::flash('success', 'New block "' . Input::get('name') . '" created.');
    return Redirect::to('/');
  }

  /**
   * Deletes a block.
   * @return type
   */
  public function deleteBlock() {
    $block = Auth::user()->blocks()->find(intval(Input::get('id')));
    if ($block) {
      Session::flash('currentPage', $block->page_id);
      $block->delete();
      Session::flash('success', 'Block deleted.');
    } else {
      Session::flash('error', 'Could not delete this block.');
    }
    return Redirect::to('/');
  }

  /**
   * Drop a block after dragging.
   *
   * @return type
   */
  public function drop() {
    $block = Auth::user()->blocks()->find(intval(Input::get('id')));
    if ($block) {
      $block->x  = intval(Input::get('x'));
      $block->y  = intval(Input::get('y'));
      $validator = Validator::make($block->toArray(), Block::$rules);
      if (!$validator->fails()) {
        $block->save();
        return Response::json(true);
      }
    }
    return Response::json(false);
  }

  /**
   * Edit a block.
   * @return type
   */
  public function editBlock() {
    $block = Auth::user()->blocks()->find(intval(Input::get('id')));
    if ($block) {
      $block->title = Input::get('title');
      $validator    = Validator::make($block->toArray(), Block::$rules);
      if (!$validator->fails()) {
        $block->save();
        Session::flash('success', 'Block edited!');
        return Redirect::to('/');
      }
      Session::flash('error', $validator->messages()->first());
      return Redirect::to('/');
    }
    Session::flash('error', 'Could not edit block!');
    return Redirect::to('/');
  }

  public function getInfo() {
    $block = Auth::user()->blocks()->find(intval(Input::get('id')));
    if ($block) {
      return Response::json($block->toArray());
    }
    return App::abort(404);
  }

}